package com.zy.springboot.service.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;
import com.zy.springboot.com.BaseUtils;
import com.zy.springboot.com.FastJsonConvert;
import com.zy.springboot.dao.system.YzmDao;
import com.zy.springboot.dao.user.UserDao;
import com.zy.springboot.entity.user.UserEntity;
import com.zy.springboot.entity.user.YzmEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by y on 2019/1/11.
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private YzmDao yzmDao;
    @Override
    public String add(String jsonData) {
        JSONObject JSONObject = JSON.parseObject(jsonData);
        UserEntity userEntity = JSON.toJavaObject(JSONObject, UserEntity.class);
        userEntity.setDelFlag(0);
        userDao.add(userEntity);
        return userEntity.getId();
    }

    @Override
    public String update(String jsonData) {
        UserEntity userEntity = JSON.toJavaObject(JSON.parseObject(jsonData), UserEntity.class);
        String result="";
        if(userDao.update(userEntity)>0){
            JSONObject user=userDao.getJSONById(userEntity.getId());
            result=BaseUtils.succsessObjRespond(user);
        }else{
            result=BaseUtils.errorrRespond("修改失败");;
        }
        return result;
    }

    @Override
    public JSONObject getUserList(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonObject.containsKey("pageSize")) {
            pageSize = jsonObject.getInteger("pageSize");
        }
        if (jsonObject.containsKey("requestPage")) {
            requestPage = jsonObject.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        List<Object> sqlArgs = new ArrayList<Object>();
        /*if (!StringUtils.isBlank(brandName)) {
           // condition.append(" AND BRAND_NAME=?");
            //sqlArgs.add(brandName);
        }*/
        condition.append("AND DEL_FLAG=0");
        List<JSONObject> records=userDao.getJSONListByPage(condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        Integer recordCount = records.size();
        int pageCount = 0;
        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / pageSize + 1);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }

        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getUserById(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String userId=jsonObject.getString("userId");
        return userDao.getJSONById(userId);
    }

    @Override
    public Boolean delById(String jsonData) {
        return userDao.delById(JSON.parseObject(jsonData).getString("id")) > 0;
    }


    @Override
    public String login(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String userName=jsonObject.getString("userName");
        String password=jsonObject.getString("password");
        String result="";
        if (!StringUtils.isBlank(userName) && !StringUtils.isBlank(password)) {
            List<JSONObject> userList=userDao.getJSONListByCondition(" AND userName=? OR TEL=? AND DEL_FLAG=0",new Object[]{userName,userName});
            if (userList==null||userList.size()<=0) {
                return BaseUtils.errorrRespond(" 该用户不存在，请检查用户名");
            }else{
                JSONObject user=userList.get(0);
                String password2=user.getString("password");
                if(password.equals(password2)){
                    result = BaseUtils.succsessArrTimeRespond(userList);
                }else{
                    result = BaseUtils.errorrRespond("用户名或密码错误");
                }
            }
        }else{
            return BaseUtils.errorrRespond(" 用户名或密码不能为空");
        }

        return result;
    }

    @Override
    public String resetPassword(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String id=jsonObject.getString("id");
        String password=jsonObject.getString("password");
        String password2=jsonObject.getString("password2");
        String oldPassword=jsonObject.getString("oldPassword");
        String result="";
        JSONObject user=userDao.getJSONById(id);
        String sysPassword=user.getString("password");
        if(!oldPassword.equals(sysPassword)){
            result = BaseUtils.errorrRespond("原密码不正确");
        }else if((password.length()>16||password.length()<6)||(password2.length()>16||password2.length()<6)){
            result = BaseUtils.errorrRespond("密码长度应为6-16位");
        }else{
            UserEntity userEntity = JSON.toJavaObject(user, UserEntity.class);
            userEntity.setPassword(password2);
            if(userDao.update(userEntity)>0){
             result=BaseUtils.succsessObjRespond("修改成功");
            }else{
              result=BaseUtils.succsessObjRespond("修改失败");
            }
        }
        return result;
    }

    @Override
    public String sendSms(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String tel=jsonObject.getString("tel");
        //生成6位验证码
        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        //发送短信
        ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "100555", "d4b96879-eda2-4b61-94c2-442dcb5b471b");
        YzmEntity yzmEntity=new YzmEntity();//数据库插入记录
        yzmEntity.setTel(tel);
        yzmEntity.setYzm(verifyCode);
        yzmDao.add(yzmEntity);  
        try{
            String result = client.send(tel,"您的验证码为:" + verifyCode + "，该码有效期为1分钟，该码只能使用一次！");
            JSONObject json = JSONObject.parseObject(result);
            if(json.getIntValue("code") != 0){
                return "fail";
            }//发送短信失败

        }catch (Exception e){
            e.printStackTrace();
        }
        return "success";
    }

    @Override
    public String yzmCheck(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String tel=jsonObject.getString("tel");
        String yzm=jsonObject.getString("yzm");
        JSONObject yzmObject = yzmDao.checkAndYzm(tel);
        if(yzmObject!=null){
            String YZM = yzmObject.getString("yzm");
            String second = yzmObject.getString("second");
            if (Integer.parseInt(second) < 60) {
                if (!StringUtils.isBlank(yzm) && yzm.equals(YZM)) {
                    return "1";// msgObject.put("flag",0);//验证成功 0
                } else {
                    return "验证码错误";
                }
            } else {
                return "验证码失效，请重新获取";
            }
        }
        return null;
    }
}
